import { reqGetCode, requserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token"
//登录和注册的模块
const state = {
    code: '',
    token: getToken(),
    userInfo: {},
};
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除本地数据
    CLEAR(state) {
        //把仓库中相关用户信息清空
        state.token = '';
        state.userInfo = {};
        //把本地存储的token清空
        removeToken();
    }
};
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //获取验证码的接口：直接把验证码返回了（为了省钱），但是正常情况，后台把验证码发到用户手机上
        let result = await reqGetCode(phone);
        //如果是发到用户手机上的，这里就不用写了
        if (result.code == 200) {
            commit("GETCODE", result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await requserRegister(user);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    //登录业务【token】
    //token :令牌，做为标志的
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        //服务器下发token，用户唯一标识符(uuid)
        //将来经常通过带token找服务器要用户信息进行展示
        if (result.code == 200) {
            commit("USERLOGIN", result.data.token);
            //持久化存储token
            setToken(result.data.token);
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    //获取用户信息,home组件派发过来的
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            //提交用户信息
            commit("GETUSERINFO", result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    //退出登录
    async userLogout({ commit }) {
        //只是向服务器，发起一次请求，通知服务器清除token
        let result = await reqLogout();
        if (result.code == 200) {
            //action里面不能操作state，要提交mutation修改
            commit("CLEAR");
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message));
        }
    }
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters,
}